package org.example.votezq.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Value("${login.sessionKey:myinfo}")
    private String sessionKey;

    // 需要登录才能访问的路径
    private static final String[] PROTECTED_PATHS = {"/vote.html", "/add.html"};

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        String requestURI = request.getRequestURI();

        // 检查当前请求的路径是否需要登录
        boolean needLogin = false;
        for (String path : PROTECTED_PATHS) {
            if (requestURI.contains(path)) {
                needLogin = true;
                break;
            }
        }

        if (!needLogin) {
            return true; // 不需要登录的路径直接放行
        }

        HttpSession session = request.getSession();
        // 判断会话中是否有登录的用户信息
        Object userInfo = session.getAttribute(sessionKey);
        if (userInfo == null) {
            // 未登录
            // 根据当前的请求类型定义响应结果
            String accept = request.getHeader("Accept");
            if (accept != null && accept.contains("application/json")) {
                // ajax请求
                response.setContentType("application/json;charset=utf-8");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                Map<String, Object> res = Map.of("code", 0, "msg", "请先登录系统");
                String json = new ObjectMapper().writeValueAsString(res);
                response.getWriter().write(json);
            } else {
                // 表单请求: 跳转到登录页面
                response.sendRedirect("/login.html");
            }
            return false;
        }

        return true; // 已登录，允许访问
    }
}